import { EventEmitter } from '../utils/EventEmitter';
import { ResourceManager } from '../resources/ResourceManager';
import { AudioManager } from '../audio/AudioManager';
import { CollisionManager } from '../physics/CollisionManager';
import { Time } from '../utils/Time';
import { Logger } from '../utils/Logger';

/**
 * 游戏主类
 */
export class Game extends EventEmitter {
    private canvas: HTMLCanvasElement;
    private ctx: CanvasRenderingContext2D;
    private isRunning: boolean = false;
    private lastTime: number = 0;
    
    public readonly resources: ResourceManager;
    public readonly audio: AudioManager;
    public readonly physics: CollisionManager;
    public readonly time: Time;
    public readonly logger: Logger;
    
    constructor(canvas: HTMLCanvasElement) {
        super();
        
        this.canvas = canvas;
        const context = canvas.getContext('2d');
        if (!context) {
            throw new Error('Failed to get 2D context from canvas');
        }
        this.ctx = context;
        
        // 初始化核心系统
        this.time = new Time();
        this.logger = new Logger();
        this.resources = new ResourceManager();
        this.audio = new AudioManager();
        this.physics = new CollisionManager();
        
        // 设置画布大小
        this.resizeCanvas();
        window.addEventListener('resize', () => this.resizeCanvas());
    }
    
    /**
     * 启动游戏
     */
    public start(): void {
        if (this.isRunning) {
            return;
        }
        
        this.isRunning = true;
        this.lastTime = performance.now();
        this.time.start();
        this.logger.info('Game started');
        
        // 开始游戏循环
        requestAnimationFrame((time) => this.gameLoop(time));
    }
    
    /**
     * 停止游戏
     */
    public stop(): void {
        if (!this.isRunning) {
            return;
        }
        
        this.isRunning = false;
        this.time.stop();
        this.logger.info('Game stopped');
    }
    
    /**
     * 游戏循环
     */
    private gameLoop(currentTime: number): void {
        if (!this.isRunning) {
            return;
        }
        
        // 计算帧间隔时间
        const deltaTime = (currentTime - this.lastTime) / 1000;
        this.lastTime = currentTime;
        
        // 更新游戏时间
        this.time.update(deltaTime);
        
        // 更新物理系统
        this.physics.update(deltaTime);
        
        // 清空画布
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        
        // 触发更新事件
        this.emit('update', { deltaTime });
        
        // 触发渲染事件
        this.emit('render', { ctx: this.ctx });
        
        // 继续下一帧
        requestAnimationFrame((time) => this.gameLoop(time));
    }
    
    /**
     * 调整画布大小
     */
    private resizeCanvas(): void {
        // 获取父元素大小
        const parent = this.canvas.parentElement;
        if (parent) {
            this.canvas.width = parent.clientWidth;
            this.canvas.height = parent.clientHeight;
        } else {
            // 如果没有父元素，使用窗口大小
            this.canvas.width = window.innerWidth;
            this.canvas.height = window.innerHeight;
        }
        
        // 触发大小改变事件
        this.emit('resize', {
            width: this.canvas.width,
            height: this.canvas.height
        });
    }
    
    /**
     * 销毁游戏实例
     */
    public destroy(): void {
        this.stop();
        
        // 销毁所有系统
        this.resources.destroy();
        this.audio.destroy();
        this.physics.destroy();
        
        // 移除事件监听
        window.removeEventListener('resize', () => this.resizeCanvas());
        this.removeAllListeners();
        
        this.logger.info('Game destroyed');
    }
} 